/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { socket } from '@kit.NetworkKit';
import { SecureContext, SecureContextOptions } from '../typeDeclaration'
import { Buffer } from './buffer'
import { BusinessError } from '@ohos.base';

export const tls = {
  connect: function(options, callback) {
    const ctsMock = {
      on: function(event, listener) {
        if (event === 'error') {
          listener(new Error('Simulated TLS connection error'));
        }
      },
    };
    callback();
    return ctsMock;
  },
};

export type TLSSocket = socket.TLSSocket

export interface PeerCertificate {
  ca: boolean;
  raw: Buffer;
  subject: Certificate;
  issuer: Certificate;
  valid_from: string;
  valid_to: string;
  serialNumber: string;
  fingerprint: string;
  fingerprint256: string;
  fingerprint512: string;
  ext_key_usage?: string[];
  subjectaltname?: string;
  infoAccess?: Dict<string[]>;
  bits?: number;
  exponent?: string;
  modulus?: string;
  pubkey?: Buffer;
  asn1Curve?: string;
  nistCurve?: string;
}

interface Certificate {
  /**
   * Country code.
   */
  C: string;
  /**
   * Street.
   */
  ST: string;
  /**
   * Locality.
   */
  L: string;
  /**
   * Organization.
   */
  O: string;
  /**
   * Organizational unit.
   */
  OU: string;
  /**
   * Common name.
   */
  CN: string;
}

interface Dict<T> {
  [key: string]: T | undefined;
}

export function getRemoteAddress(tls):socket.NetAddress | null{
  tls.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => {
    if (err) {
      console.log('getRemoteAddress fail');
      return;
    }
    console.log('getRemoteAddress success:' + JSON.stringify(data));
    return data
  });
}

export function createSecureContext(options?: SecureContextOptions): SecureContext{
  return {context: options};
}

export function getCipher() {
  return {
    name: 'mock-cipher-suite',
    version: 'mock-version',
    standardName: 'TLS_AES_256_GCM_SHA384',
  };
}

export interface CipherNameAndProtocol {
  /**
   * The cipher name.
   */
  name: string;
  /**
   * SSL/TLS protocol version.
   */
  version: string;
  /**
   * IETF name for the cipher suite.
   */
  standardName: string;
}

// mock
export function checkServerIdentity(hostname: string, cert: PeerCertificate) {

}
